//
//  WriteMessageViewController.m
//  金融
//
//  Created by Apple on 2017/11/10.
//  Copyright © 2017年 Apple. All rights reserved.
//

#import "WriteMessageViewController.h"
#import "HFTextView.h"

@interface WriteMessageViewController ()<UITextViewDelegate>
{
    //备注文本View高度
    float noteTextHeight;
    float pickerViewHeight;
    float allViewHeight;
}
@property (nonatomic, strong)HFTextView *noteTextView;
@property (nonatomic, strong)UIButton    *rightItem;
@property (nonatomic, strong)NSMutableArray * dataArray;
@end

@implementation WriteMessageViewController
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.barView addSubview:self.titleL];
    [self.titleL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.barView);
        make.width.mas_lessThanOrEqualTo(SCREENWIDTH - 100);
        make.height.mas_greaterThanOrEqualTo(10);
    }];
    self.titleL.text = @"留言";
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    
    self.scrollView = [UIScrollView new];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.scrollView];
    
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.barView.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom);
        }else{
            make.bottom.mas_equalTo(self.view.mas_bottom);
        }
    }];
    [self initViews];
    [self.noteTextView becomeFirstResponder];
}

#pragma mark - NavigationBar
- (UIButton *)rightItem
{
    if (!_rightItem) {
        _rightItem = [[UIButton alloc] init];
        [_rightItem setTitleColor:SELECTCOLOR forState:UIControlStateNormal];
        [_rightItem setBackgroundColor:TITLEColor];
        _rightItem.layer.cornerRadius = 5.f;
        _rightItem.layer.masksToBounds = YES;
        [_rightItem setTitle:@"发送" forState:UIControlStateNormal];
        [_rightItem addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightItem;
}
- (void)clickBackAction
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
- (void)clickAction:(id)sender
{
    [self submitToServer];
}

- (void)viewTapped{
    [self.view endEditing:YES];
}

- (void)initViews{
    
    _noteTextBackgroudView = [[UIView alloc]init];
    _noteTextBackgroudView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
    
    _noteTextView = [[HFTextView alloc]init];
    _noteTextView.textColor = TEXTColor;
//    _noteTextView.myPlaceholder = @"这一刻的想法....";
//    _noteTextView.myPlaceholder = @"";
//    _noteTextView.myPlaceholderColor = SUBTEXTColor;
    
    _noteTextView.delegate = self;
    _noteTextView.font = [UIFont boldSystemFontOfSize:14];
    
    _textNumberLabel = [UILabel new];
    _textNumberLabel.font = FONT(11);
    _textNumberLabel.textAlignment = NSTextAlignmentRight;
    [_scrollView addSubview:_noteTextBackgroudView];
    [_scrollView addSubview:_noteTextView];
    [_scrollView addSubview:_textNumberLabel];
    [self.scrollView addSubview:self.rightItem];
    [self updateViewsFrame];
}

- (void)updateViewsFrame{
    
    if (!allViewHeight) {
        allViewHeight = 0;
    }
    if (!noteTextHeight) {
        noteTextHeight = 150;
    }
    
    _noteTextBackgroudView.frame = CGRectMake(0, 0, SCREENWIDTH, noteTextHeight);
    
    //文本编辑框
    _noteTextView.frame = CGRectMake(15, 15, SCREENWIDTH - 30, noteTextHeight);
    _noteTextView.layer.cornerRadius = 5.f;
    _noteTextView.layer.masksToBounds = YES;
    _noteTextView.layer.borderWidth = 0.5f;
    _noteTextView.layer.borderColor = LINEColor.CGColor;
    
    //文字个数提示Label
//    _textNumberLabel.frame = CGRectMake(0, _noteTextView.frame.origin.y + _noteTextView.frame.size.height-15, SCREENWIDTH-10, 15);
    [_textNumberLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.noteTextView);
        make.right.mas_equalTo(self.noteTextView.mas_right).offset(-3);
        make.height.mas_equalTo(16);
        make.width.mas_greaterThanOrEqualTo(10);
    }];
    [self.rightItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.noteTextView);
        make.top.mas_equalTo(self.textNumberLabel.mas_bottom).offset(20);
        make.height.mas_offset(40);
    }];
    allViewHeight = noteTextHeight + _textNumberLabel.frame.size.height + 100;
    
    self.scrollView.contentSize = CGSizeMake(0,allViewHeight);
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/300    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 300) {
        _textNumberLabel.textColor = [UIColor redColor];
    }
    else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    [self textChanged];
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
    }
    return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView{
    _textNumberLabel.text = [NSString stringWithFormat:@"%lu/300    ",(unsigned long)_noteTextView.text.length];
    if (_noteTextView.text.length > 300) {
        _textNumberLabel.textColor = [UIColor redColor];
    }else{
        _textNumberLabel.textColor = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1.0];
    }
    [self textChanged];
}

-(void)textChanged{
    CGRect orgRect = self.noteTextView.frame;//获取原始UITextView的frame
    CGSize size = [self.noteTextView sizeThatFits:CGSizeMake(self.noteTextView.frame.size.width, MAXFLOAT)];
    orgRect.size.height=size.height+10;//获取自适应文本内容高度
    if (orgRect.size.height > 100) {
        noteTextHeight = orgRect.size.height;
    }
    [self updateViewsFrame];
}
#pragma maek - 检查输入
- (BOOL)checkInput{
    if (_noteTextView.text.length == 0) {
        //MBhudText(self.view, @"请添加记录备注", 1);
        return NO;
    }
    return YES;
}

#pragma mark - 上传数据到服务器
- (void)submitToServer
{
    NSLog(@"%@",self.dict);
    if(self.noteTextView.text.length > 0){
        self.rightItem.enabled = NO;
        if(self.type == WriteInfoType){  
            NSString * url = [NSString stringWithFormat:@"%@/%@",self.dict[@"target"][@"request"][@"url"],self.dict[@"target"][@"request"][@"data"][@"id"]];
            NSDictionary * para = @{@"body":self.noteTextView.text};
            [self requestMethod:self.dict[@"target"][@"request"][@"method"] url:url data:para];
        }else{
            NSString * url = [NSString stringWithFormat:@"%@",self.dict[@"target"][@"request"][@"url"]];
            NSDictionary * para = @{@"body":self.noteTextView.text,
                                    @"sectionId":self.dict[@"target"][@"request"][@"data"][@"sectionId"]
                                    };
            [self requestMethod:self.dict[@"target"][@"request"][@"method"] url:url data:para];
        }
    }
}
- (void)requestMethod:(NSString *)method url:(NSString *)url  data:(NSDictionary *)data
{
    WeakSelf
//    NSString *textJS = @"tw.getNew()";
    if ([method isEqualToString:@"POST"]) {
        [HttpRequest postWithURLString:url parameters:data showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
            weakSelf.rightItem.enabled = YES;
            [MyObject failedPrompt1:responseObject[@"message"]];
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                if(weakSelf.clickMessageBlock){
                    weakSelf.clickMessageBlock();
                }
            }];
        } failure:^(NSError * _Nullable error) {
            weakSelf.rightItem.enabled = YES;
            NSLog(@"%@",error);
        } login:^(BOOL isLogin) {
            weakSelf.rightItem.enabled = YES;
        }];
    }
    if ([method isEqualToString:@"GET"]) {
        [HttpRequest getWithURLString:url parameters:data showProgressHud:YES success:^(NSDictionary * _Nullable responseObject) {
            weakSelf.rightItem.enabled = YES;
            [MyObject failedPrompt1:responseObject[@"message"]];
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                if(weakSelf.clickMessageBlock){
                    weakSelf.clickMessageBlock();
                }
            }];
        } failure:^(NSError * _Nullable error) {
            weakSelf.rightItem.enabled = YES;
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
